<template>
  <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="100px">
    <el-row :gutter="20">
      <el-col :span="15">
        <h3>基本信息</h3>
        <el-card>
          <el-row :gutter="20" type="flex" style="flex-wrap:wrap; flex-direction: row">
            <el-col :span="12">
              <el-form-item label="题库名称" prop="title">
                <el-input v-model="postForm.title" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="题库分类">
                <dic-catalog-tree v-model="postForm.catId" dic-code="repo_catalog" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="根知识点">
                <key-point-tree-select v-model="postForm.pointCode" :multiple="false" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="作用范围">
                <el-checkbox v-model="postForm.forExam" label="用于考试" />
                <el-checkbox v-model="postForm.forTrain" label="用于训练" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="题库简介" prop="remark">
                <el-input v-model="postForm.remark" type="textarea" rows="10" maxlength="250" show-word-limit />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <div v-if="postForm.forTrain">
          <h3>训练权限</h3><el-card>
            <el-radio-group v-model="postForm.openType" size="small">
              <el-radio :label="1">
                完全公开
              </el-radio>
              <el-radio :label="3">
                部分学员
              </el-radio>
            </el-radio-group>
            <div style="padding-top: 20px">
              <div v-if="postForm.openType===1">
                <el-alert title="开放的，任何人都可以进行训练！" type="warning" />
              </div>
              <div v-if="postForm.openType===3">
                <user-range :users.sync="postForm.userList" :departs.sync="postForm.deptCodes" :groups.sync="postForm.groupIds" />
              </div>
            </div>
          </el-card>
        </div>
        <div style="margin-top: 20px">
          <el-button type="primary" @click="submitForm">
            保存
          </el-button> <el-button type="info" @click="onCancel">
            返回
          </el-button>
        </div>
      </el-col>
      <el-col :span="9">
        <el-row>
          <el-col>
            <h3 style="display: inline-block">章节管理</h3>
            <el-button type="primary" icon="el-icon-plus" size="small" style="float: right; margin-block-start: 1em;margin-block-end: 1em;" @click="addChapter">
              添加
            </el-button>
          </el-col>
          <el-col>
            <el-card style=" overflow-y: auto">
              <el-table :data="postForm.chapters" height="calc(100vh - 260px)" row-key="id">
                <el-table-column prop="title" label="章节名称">
                  <template v-slot="scope">
                    <el-input v-model="scope.row.title" />
                  </template>
                </el-table-column>
                <el-table-column prop="quCount" align="center" label="试题数量" width="100px" />
                <el-table-column label="操作" width="120px" align="center">
                  <template v-slot="scope">
                    <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="removeChapter(scope.$index, scope.row.quCount)" /> <el-tooltip effect="dark" content="按住鼠标调整到合适的位置后释放" placement="top-start">
                      <el-button size="mini" icon="el-icon-rank" circle />
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>

import Sortable from 'sortablejs'
import { fetchDetail, saveData } from '@/api/repo/repo'
import { mapGetters } from 'vuex'
import DicListSelect from '@/components/DicListSelect/index.vue'
import KeyPointTreeSelect from '@/components/KeyPointTreeSelect/index.vue'

export default {
  name: 'RepoAdd',
  components: { KeyPointTreeSelect, DicListSelect },
  data() {
    return {
      postForm: {
        catId: '',
        chapters: [],
        pointCode: '',
        forExam: true,
        forTrain: true,
        openType: 1,
        price: 0
      },
      loading: false,
      rules: {

        title: [
          { required: true, message: '题库名称不能为空！' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'siteData'
    ])
  },
  mounted() {
    // 阻止默认行为
    document.body.ondrop = function(event) {
      event.preventDefault()
      event.stopPropagation()
    }
    // 拖动表格
    this.initSort()
  },
  created() {
    const id = this.$route.params.id
    if (id !== undefined) {
      this.fetchData(id)
    }
  },
  methods: {

    // 初始化表格
    initSort() {
      // 存在即销毁
      if (this.sortTable) {
        this.sortTable.destroy()
      }

      // 拖动表格
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const that = this
      this.sortTable = Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          if (newIndex === oldIndex) {
            return
          }
          that.postForm.chapters.splice(
            newIndex,
            0,
            that.postForm.chapters.splice(oldIndex, 1)[0]
          )
          const newArray = that.postForm.chapters.slice(0)
          that.postForm.chapters = []
          that.$nextTick(function() {
            that.postForm.chapters = newArray
          })
        }
      })
    },

    // 添加子项
    handleAdd() {
      this.postForm.answerList.push({ isRight: false, content: '', analysis: '' })
    },

    fetchData(id) {
      const params = { id: id }
      fetchDetail(params).then(res => {
        this.postForm = res.data
      })
    },

    submitForm() {
      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          return
        }

        saveData(this.postForm).then(() => {
          this.$notify({
            title: '成功',
            message: '题库保存成功！',
            type: 'success',
            duration: 2000
          })

          // 清理缓存
          localStorage.clear()

          // 清理缓存
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.push({ name: 'RepoList' })
        })
      })
    },

    onCancel() {
      this.$router.push({ name: 'RepoList' })
    },

    addChapter() {
      this.postForm.chapters.push({ title: '新章节' })
    },

    removeChapter(index, quCount) {
      if (quCount > 0) {
        // 删除
        this.$confirm('此前挂靠在此章节下试题章节属性将被置空，确认要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.postForm.chapters.splice(index, 1)
        })
      } else {
        this.postForm.chapters.splice(index, 1)
      }
    }

  }
}
</script>
